package com.quanyan.ic.protocol.client.handler;

import com.quanyan.ic.protocol.Code;
import com.quanyan.ic.protocol.LightCmd;
import com.quanyan.ic.protocol.MessageType;
import com.quanyan.ic.protocol.codec.protobuf.ICMessageProto;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * Created by zhuo.shi on 2017/6/7.
 */
public class LightCmdReqHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ICMessageProto.ICMessage icMessage = (ICMessageProto.ICMessage) msg;
        if (icMessage.getHeader() != null && icMessage.getHeader().getType() == MessageType.SERVICE_REQ.value()) {
            System.out.println("----------biz msg");
            ICMessageProto.ICMessage msg2 = buildBizICMessage(icMessage.getBody().getOrderNo(), icMessage.getHeader().getPid(), icMessage.getBody().getSid(), LightCmd.ON);
            System.out.println("return: " + msg2);
            ctx.writeAndFlush(msg2);
        } else {
            ctx.fireChannelRead(msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.fireExceptionCaught(cause);
    }

    private ICMessageProto.ICMessage buildBizICMessage(String orderNo, int placeId, int siteId, LightCmd lightCmd) {
        ICMessageProto.ICMessage.Builder builder = ICMessageProto.ICMessage.newBuilder();
        ICMessageProto.ICMessage.Header.Builder hbuilder = ICMessageProto.ICMessage.Header.newBuilder();
        hbuilder.setProtocolVersion(0xAF1);
        hbuilder.setPid(placeId);
        hbuilder.setType(MessageType.SERVICE_REQ.value());
        hbuilder.setRespCode(Code.RC_200.value());

        ICMessageProto.ICMessage.Body.Builder bbuilder = ICMessageProto.ICMessage.Body.newBuilder();
        bbuilder.setOrderNo(orderNo);
        bbuilder.setSid(siteId);
        bbuilder.setTf(lightCmd.value());
        bbuilder.setSc(Code.DEFAULT.value());
        bbuilder.setSc(Code.SC_300.value());
        builder.setHeader(hbuilder.build());
        builder.setBody(bbuilder.build());

        return builder.build();
    }
}
